package no.evalanche.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.http.AndroidHttpClient;
import android.os.Handler;
import android.util.Log;

public class MultipleChoiceIO extends MC_Async {
	

	public MultipleChoiceIO(String s, Handler h) {
		sessionid = s;
		handler = h;
	}

	@Override
	protected JSONObject doInBackground(EntityList ... pams) {
		JSONObject jsonarray = null;		
		AndroidHttpClient httpclient = AndroidHttpClient.newInstance("android");
		HttpPost request = new HttpPost(ServiceList.URL.toString());
		request.setHeader("Cookie","sessionid="+sessionid);		
		try {  
			request.setEntity(new UrlEncodedFormEntity(pams[0]));
			HttpResponse r = httpclient.execute(request);
			jsonarray = jsonFromEntity(r);			
			httpclient.close();
		} catch (IOException e) {
			Log.d("EvalancheAuthenticator",
					"Feil i doInBackground! " + e.toString());
		}
		return jsonarray;
	}
	
	private JSONObject jsonFromEntity(HttpResponse r) throws IOException {
		HttpEntity httpEntity = r.getEntity();
		BufferedReader br = new BufferedReader(new InputStreamReader(
				httpEntity.getContent()));
		String line;
		StringBuilder builder = new StringBuilder();
		while ((line = br.readLine()) != null) {
			builder.append(line);
		}
		try {
			JSONArray jar = new JSONArray(builder.toString());
			JSONObject job = new JSONObject();
			job.accumulate("challengelist", jar);
			return job;
		} catch (JSONException e) {
			return new JSONObject();
		}
	}

	
	

}
